package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.UploaderResponse;
import com.sdruixinggroup.mondayb2b.utils.DisplayUtil;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.ui.MineDetailActivity.IMAGE_REQUEST_CODE;

/**
 * Created by 00029935 on 2017/12/11.
 */

public class OffLinePayFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.title_view)
    RelativeLayout titleView;
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    Unbinder unbinder;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_order_cash)
    TextView tvOrderCash;
    @BindView(R.id.loading)
    ProgressBar loading;
    private String pic = "";
    private double cash;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cash = getActivity().getIntent().getDoubleExtra("cash", 0);
    }

    @Override
    protected int getInflateLayout() {
        return R.layout.nong_zi_pay_fragment;
    }

    @Override
    protected void setUpView(View view) {
        tvTitle.setText("填写订货单");
        tvOrderCash.setText("订单金额 ¥ " + DisplayUtil.double2String(cash) );
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.ib_back, R.id.iv_pic, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                getActivity().finish();
                break;
            case R.id.iv_pic:
                initgetPhotoview();
                break;
            case R.id.tv_commit:
                if (!TextUtils.isEmpty(pic)) {
                    Intent intent = new Intent();
                    intent.putExtra("value", pic);
                    getActivity().setResult(Activity.RESULT_OK, intent);
                    getActivity().finish();
                }else {
                    showMsgToast("请上传打款凭证图片");
                }
                break;
        }
    }


    private void initgetPhotoview() {
        Intent intent = new Intent(getContext(), MultiImageSelectorActivity.class);
        // whether show camera
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // max select image amount
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // select mode (MultiImageSelectorActivity.MODE_SINGLE OR MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case IMAGE_REQUEST_CODE:

                ArrayList<String> selectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if (selectPath != null && selectPath.size() > 0) {
                    for (int i = 0; i < selectPath.size(); ++i) {

                        Glide.with(getContext()).load(selectPath.get(i)).into(ivPic);
                        String picurl = compressUploadPicture(selectPath.get(i));
                        uploadPic(picurl);
                    }
                }
        }
    }

    private void uploadPic(String picurl) {
        loading.setVisibility(View.VISIBLE);
        String url = API.UPLOAD + UserInfoUtil.getInfoToken(getContext());
        HashMap<String, String> heades = new HashMap<>();
        heades.put("Accept", "*/*");
        TypeToken<UploaderResponse> typeToken = new TypeToken<UploaderResponse>() {
        };
        File file = new File(picurl);
        OkHttpUtils.post()//
                .addFile("mFile", file.getName(), file)
                .url(url)
                .headers(heades)//
                .build()//
                .execute(new ObjectCallBack<UploaderResponse>(typeToken) {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(UploaderResponse response, int id) {
                        if (response.getErr_code() == 0) {
                            pic = response.getResult().getMFile();

                        }
                        loading.setVisibility(View.GONE);
                    }
                });
    }

    @OnClick(R.id.tv_right)
    public void onClick() {


    }

    public final static int compressBySizeWidth = 720;
    public final static int compressBySizeHeight = 1280;
    private String  compressUploadPicture(String imagePath) {

        String compressPath = Environment.getExternalStorageDirectory()
                + File.separator + SystemClock.currentThreadTimeMillis()+ ".jpg";
        File file = new File(imagePath);
        if (file.exists()) {
            Bitmap bitmap = compressBySize(imagePath, compressBySizeWidth,
                    compressBySizeHeight);
            // 保存图片
            try {
                saveFile(bitmap, compressPath);
            } catch (Exception e) {
                e.printStackTrace();
            }

            return compressPath;
        }else {
            return null;
        }
    }


    // 压缩图片尺寸
    public Bitmap compressBySize(String pathName, int targetWidth,
                                 int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);

        bitmap = rotateBitmapByDegree(bitmap, getImageDegree(pathName));
        return bitmap;
    }

    // 存储进SD卡
    public void saveFile(Bitmap bm, String fileName) throws Exception {
        File dirFile = new File(fileName);
        // 检测图片是否存在
        if (dirFile.exists()) {
            dirFile.delete(); // 删除原图片
        }
        File myCaptureFile = new File(fileName);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        // 100表示不进行压缩，70表示压缩率为30%
        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
    }



    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm
     *            需要旋转的图片
     * @param degree
     *            旋转角度
     * @return 旋转后的图片
     */
    public Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    private int getImageDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
}
